import React from 'react'
import { RiStarSFill } from '@remixicon/react'
import { withNativeProps } from '../../utils/native-props'
import { usePropsValue } from '../../hooks/use-props-value'
import { CheckListProvider } from './context'
import List from '../List'
import type { CheckListValue, CheckListProps } from './type'

export const CheckList: React.FC<CheckListProps> = (props) => {
  const {
    activeIcon = <RiStarSFill />,
    defaultValue = [],
    disabled = false,
    extra,
    isLink = false,
    mode,
    multiple = false,
    onChange,
    readOnly = false,
    value,
    children,
  } = props

  const [actValue, setActValue] = usePropsValue({
    value,
    defaultValue,
    onChange,
  })

  const check = (val: CheckListValue) => {
    if (multiple) {
      setActValue([...actValue, val])
    } else {
      setActValue([val])
    }
  }

  const uncheck = (val: CheckListValue) => {
    setActValue(actValue.filter((item: CheckListValue) => item !== val))
  }

  return (
    <CheckListProvider
      value={{
        activeIcon,
        check,
        disabled,
        extra,
        isLink,
        readOnly,
        uncheck,
        value: actValue,
      }}
    >
      {withNativeProps(
        props,
        <List mode={mode}>
          {children}
        </List>,
      )}
    </CheckListProvider>
  )
}
